package com.hph.health.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hph.health.common.BaseResponse;
import com.hph.health.common.ErrorCode;
import com.hph.health.common.ResultUtils;
import com.hph.health.exception.BusinessException;
import com.hph.health.exception.ThrowUtils;
import com.hph.health.model.entity.Order;
import com.hph.health.model.entity.ProductComment;
import com.hph.health.service.OrderService;
import com.hph.health.service.ProductCommentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author hanph
 * @from haut
 */
@RestController
@RequestMapping("/productcomment")
@Slf4j
public class ProductCommentController {
    @Resource
    private ProductCommentService productCommentService;

    @Resource
    private OrderService orderService;

    /**
     * 分页获取图片（仅管理员）
     *
     * @return
     */
    @GetMapping("/list")
    public BaseResponse<List<ProductComment>> listProductByPage(long id) {
        QueryWrapper<ProductComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", id);
        List<ProductComment> productPicInfoList = productCommentService.list(queryWrapper);
        return ResultUtils.success(productPicInfoList);
    }

    /**
     *  新增评论
     *
     * @param productComment
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Integer> addproductComment(@RequestBody ProductComment productComment) {
        if (productComment == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = productCommentService.save(productComment);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(productComment.getCommentId());
    }

    /**
     * 查看用户是否买了此商品
     *
     * @param order
     * @return
     */
    @PostMapping("/orbuy")
    public BaseResponse<Long> orBuy(@RequestBody Order order) {
        if (order == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", order.getProductId());
        queryWrapper.eq("user_id", order.getUserId());
        Order result = orderService.getOne(queryWrapper, true);
        if (result == null) {
            return ResultUtils.success(0L);
        }
        return ResultUtils.success(result.getId());
    }
}
